package com.cynteka.cyfoman.core.collection;

import com.cynteka.cyfoman.core.ComplexPropertyResolver;
import com.cynteka.cyfoman.core.IPropertyResolver;
import com.cynteka.cyfoman.core.ValueObject;
import com.cynteka.cyfoman.core.config.ColumnMD;

import java.util.*;

/**
 * User: Sergey
 * Date: 06.08.11
 * Time: 13:49
 */
public class CollectionIntersection extends BaseCollection<ValueObject> {

    private List<String> collectionIds;
    private IPropertyResolver propertyResolver = new ComplexPropertyResolver();
    private String keyColumn;
    private List<ColumnMD> columns;

    public CollectionIntersection(String id) {
        super(id);
    }

    @Override
    public Collection<ValueObject> getItems(Map<String, Object> params) {
        Set keys = new HashSet();
        Collection<ValueObject> res = new ArrayList<ValueObject>();
        for(String collectionId : collectionIds) {
            ICollection collection = getOwner().getCollection(collectionId);
            Collection items = collection.getItems(params);
            for(Object item : items) {
                Object keyValue = propertyResolver.getProperty(item, keyColumn);
                if(!keys.contains(keyValue)) {
                    ValueObject valueObject = new ValueObject();
                    valueObject.setId(keyValue);
                    keys.add(keyValue);
                    for(ColumnMD columnMD : columns) {
                        String columnName = columnMD.getName();
                        Object value = propertyResolver.getProperty(item, columnName);
                        valueObject.setParam(columnName, value);
                    }
                    res.add(valueObject);
                }
            }
        }
        return res;
    }
}
